using System;
using System.Windows;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace JGSY.CourseManagement.SharedKernel.Exceptions.ExceptionHandling
{
    /// <summary>
    /// 全局异常处理器
    /// </summary>
    public class ExceptionHandler
    {
        private readonly ILogger<ExceptionHandler> _logger;

        /// <summary>
        /// 初始化异常处理器
        /// </summary>
        /// <param name="logger">日志服务</param>
        public ExceptionHandler(ILogger<ExceptionHandler> logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="ex">待处理的异常</param>
        /// <param name="message">自定义错误消息</param>
        public void HandleException(Exception ex, string message = "发生未处理异常")
        {
            if (ex == null) throw new ArgumentNullException(nameof(ex));

            _logger.LogError(ex, "{Message}", message);
            // 可以添加额外的异常处理逻辑，如显示错误对话框、发送错误报告等
        }

        /// <summary>
        /// 异步处理异常
        /// </summary>
        /// <param name="ex">待处理的异常</param>
        /// <param name="message">自定义错误消息</param>
        public async Task HandleExceptionAsync(Exception ex, string message = "发生未处理异常")
        {
            if (ex == null) throw new ArgumentNullException(nameof(ex));

            _logger.LogError(ex, "{Message}", message);
            // 可以添加异步的异常处理逻辑
            await Task.CompletedTask;
        }

        /// <summary>
        /// 注册全局异常处理程序
        /// </summary>
        public void RegisterGlobalHandlers()
        {
            // 注册应用程序域未处理异常
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                var exception = e.ExceptionObject as Exception;
                HandleException(exception ?? new Exception("发生未知异常"), "应用程序域未处理异常");
            };

            // 注册Dispatcher未处理异常
            if (System.Windows.Application.Current != null)
            {
                System.Windows.Application.Current.DispatcherUnhandledException += (sender, e) =>
                {
                    HandleException(e.Exception, "UI线程未处理异常");
                    e.Handled = true; // 标记为已处理，防止应用程序崩溃
                };
            }
            else
            {
                _logger.LogWarning("Application.Current为null，无法注册Dispatcher异常处理程序");
            }

            // 注册任务调度器未观察到的异常
            TaskScheduler.UnobservedTaskException += (sender, e) =>
            {
                HandleException(e.Exception, "任务调度器未观察到的异常");
                e.SetObserved(); // 标记为已观察，防止应用程序终止
            };

            _logger.LogInformation("全局异常处理程序已注册");
        }
    }
}